package com.softaria.promosite.server;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.softaria.server.seo.StaticMenu;
import com.softaria.server.seo.StaticPagesFactory;
import com.softaria.windows.logic.URLParser;
import com.softaria.windows.model.ModelUrl;
import com.softaria.windows.model.ViewUrl;
import com.softaria.windows.seo.HttpParametersConstants;

public class FineUrlRedirector extends HttpServlet implements HttpParametersConstants {

	private static final String STATIC_CONTROLLER_MAPPING = "staticControllerMapping";
	
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String pathInfo = req.getPathInfo();
		String queryString = req.getQueryString();
		String contextPath = req.getContextPath();

		String uri = buildURI(pathInfo, queryString);

		//System.out.print("@@@@@@@@@@@@@@@@@@2uri="+uri);
		
		ModelUrl url = null;
		if (uri != null) {
			url = URLParser.parse(uri);
		}

		if (url == null) {
			url = getDefaultUrl();
		}
		
		//ystem.out.print("@@@@@@@@@@@@@@@@@@2url="+url.toString());
		
		String location = (contextPath == null ? "" : contextPath) + "/"+getServletConfig().getInitParameter(STATIC_CONTROLLER_MAPPING)+"?"+HTTP_PARAMETER_PERSPECTIVE+"="+url.getPerspectiveId();
		
		//System.out.print("@@@@@@@@@@@@@@@@@@2location="+location);
		
		if(url.isView()) {
			location+="&"+HTTP_PARAMETER_VIEW+"="+((ViewUrl)url).getViewId();
			location+="&"+HTTP_PARAMETER_VIEWPARAM+"="+resp.encodeRedirectURL(((ViewUrl)url).getParameters());
		}

		//System.out.println("Redirecting to url: "+location);
		
		resp.sendRedirect(location);
	}

	private String buildURI(String pathInfo, String queryString) {
		String uri = null;

		if ((pathInfo != null) && (pathInfo.trim().length() != 0)) {

			uri = pathInfo;

			if ((queryString != null) && (queryString.trim().length() != 0)) {
				uri += "?" + queryString;
			}

			if (uri.startsWith("/")) {
				uri = uri.substring(1);
			}

		}
		return uri;
	}

	private ModelUrl getDefaultUrl() {
		StaticMenu menu = StaticPagesFactory.getInstance().getMenu();
		if (menu != null) {
			return menu.getMenuConfiguration().getDefaultPerspective();
		} else {
			return null;
		}
	}

}
